#!/usr/bin/perl -w
# check mysqld status and record response time(ms)
# @param $1 install home
# @param $2 delimiter
# @param $3 host
# @param $4 port
# @param $5 username
# @param $6 password
# DavidLi 2009-06-17  -- denied to use localhost connect mysqld if have multi mysqld on same host,it will cause wrong statistic 
# DavidLi 2009-06-17  -- Add  em_error message if acess denied
# DavidLi 2009-06-17  -- modify response time algorithm with  select benchmark(10000,md5('test_response_time')) 
# DavidLi 2009-06-17  --"exit 1" cause  metric error even if  normal exit
# XieWen  2006-09-30  -- initial 
use strict;
use Time::HiRes qw( gettimeofday tv_interval );

my ($MYSQL_HOME,$DELIM,$HOST,$PORT,$USER,$PASS) = @ARGV;
my $PARAM="";
$PARAM="$PARAM -h\"$HOST\"" if (defined($HOST) && $HOST ne "");
$PARAM="$PARAM -P\"$PORT\"" if (defined($PORT) && $PORT ne "");
$PARAM="$PARAM -u\"$USER\"" if (defined($USER) && $USER ne "");
$PARAM="$PARAM -p\"$PASS\"" if (defined($PASS) && $PASS ne "");
my $MYSQL="$MYSQL_HOME/bin/mysql";
my $MYSQLADMIN="$MYSQL_HOME/bin/mysqladmin";
if ($^O =~ m/MSWin32/) {
  $MYSQL =~ s/\//\\/g;
  $MYSQLADMIN =~ s/\//\\/g;
}

# denied to use localhost
if ( $HOST eq "localhost" || $HOST =~/^127\.0*0/) {
   print "em_error=denied to use localhost\n";
   print "em_result=Down\n";
   exit 0;
}

# Check if mysqld is alive
my $retmsg=`$MYSQLADMIN $PARAM ping 2>&1`;
chomp($retmsg);

# access denied return em_error with error message
if ( $retmsg =~ /Access denied/ ) {
   print "em_error=$retmsg\n";
   print "em_result=DowN\n";
   exit 0;
}

# if down ,display status and exit
if ( "$retmsg" ne "mysqld is alive" ) {
    print "em_result=Down\n";
    print "em_error=$retmsg\n";
    exit 0;
}

#if up, compute response time (ms)
my $time_begin = [gettimeofday()];
my $ret = system("$MYSQL $PARAM  >/dev/null <<-!
  select benchmark(10000,md5('test_response_time'));
!");
my $duration = int(tv_interval($time_begin) * 1000);
print "em_result=Up${DELIM}${duration}\n";
exit 0;

